<template>
  <div class="app-container basicfile-box">
    <el-row :gutter="20">
      <el-col :xs="24" :sm="6" :md="6" :lg="4">
        <!-- 搜索 -->
        <el-input
          v-hasPermi="['inv:items:query']"
          v-model="searchName"
          placeholder="请输入分类名称"
          clearable
          size="small"
          prefix-icon="el-icon-search"
          style="margin-bottom: 10px"
        />
        <!-- 分类数据 -->
        <Tree
          ref="tree"
          :sortTree="sortTree"
          :isHeight="isHeight"
          :loading="treeLoading"
          :isOperation="isOperation"
          @nodeClick="nodeClick(arguments)"
          :searchName="searchName"
        />
      </el-col>
      <!-- 搜索数据 -->
      <el-col :span="20" :xs="24">
        <el-form
          :inline="true"
          label-width="68px"
          style="margin-bottom: 15px"
          v-hasPermi="['inv:items:query']"
        >
          <el-form-item label="物料编码">
            <el-input
              v-model="searchForm.searchCode"
              clearable
              size="small"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item label="物料名称">
            <el-input
              v-model="searchForm.searchName"
              clearable
              size="small"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              v-hasPermi="['inv:items:query']"
              type="primary"
              icon="el-icon-search"
              @click="search"
              >搜索
            </el-button>
            <el-button
              v-hasPermi="['inv:items:query']"
              icon="el-icon-refresh"
              @click="serchReset()"
              >重置
            </el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8 operation-btn">
          <el-col :span="1.5">
            <el-button
              type="primary"
              v-hasPermi="['inv:items:query']"
              plain
              icon="el-icon-menu"
              size="mini"
              @click="checkleAll"
              >查询所有</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="addMaterial"
              v-hasPermi="['inv:items:add']"
              >新增</el-button
            >
            <el-button
              type="primary"
              plain
              icon="el-icon-circle-check"
              v-hasPermi="['inv:items:check']"
              size="mini"
              @click="btnDuplicat"
              :disabled="disCuarent"
              >查重</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-remove-outline"
              size="mini"
              @click="handlEmpty"
              :disabled="disCuarent"
              v-hasPermi="['inv:items:dump']"
              >清空</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="handleImport"
              :disabled="disCuarent"
              v-hasPermi="['inv:items:import']"
              >导入</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['inv:items:export']"
              >导出</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-printer"
              size="mini"
              @click="handlePrint"
              v-hasPermi="['inv:items:print']"
              >打印</el-button
            >
          </el-col>
        </el-row>
        <!-- 打印数据 -->
        <PrintPage :printData="printData" ref="startPrint" :title="printName" />
        <!-- 物料数据 -->
        <el-table
          v-loading="loading"
          :data="basicfileList"
          border
          :height="maxHeight"
        >
          <el-table-column type="index" width="60" align="center" label="序号">
          </el-table-column>
          <el-table-column label="物料编码" align="center" sortable prop="code">
            <template slot="header" slot-scope="scope">
              <div class="search-box">
                <transition name="toggle-fade" class="no-print">
                  <div class="box-input" v-show="inputStatusCode">
                    <div class="input-t">
                      <el-input
                        size="mini"
                        placeholder="请输入物料编码"
                        v-model="headerFrom.codeInput"
                        @keyup.enter.native="searchCodeName('code', scope)"
                      />
                    </div>
                  </div>
                </transition>
                <div class="search-header">
                  <span>物料编码</span>
                  <i
                    class="el-icon-search no-print"
                    @click.stop="handleCodeName('code')"
                    v-if="!inputStatusCode"
                  ></i>
                  <i
                    class="el-icon-close no-print"
                    @click.stop="handleClose('code')"
                    v-if="inputStatusCode"
                  ></i>
                </div>
              </div>
            </template>
            <template slot-scope="scope">
              <span @click.stop="seeMaterial(scope.row)">{{
                scope.row.code
              }}</span>
            </template>
          </el-table-column>
          <el-table-column label="物料名称" align="center" prop="name" sortable>
            <template slot="header" slot-scope="scope">
              <div class="search-box">
                <transition name="toggle-fade">
                  <div
                    class="box-input"
                    v-show="inputStatusName"
                    @click.stop="stopReturn"
                  >
                    <div class="input-t">
                      <el-input
                        size="mini"
                        placeholder="请输入物料名称"
                        v-model="headerFrom.nameInput"
                        @keyup.enter.native="searchCodeName('name', scope)"
                      />
                    </div>
                  </div>
                </transition>
                <div class="search-header">
                  <span>物料名称</span>
                  <i
                    class="el-icon-search"
                    @click.stop="handleCodeName('name')"
                    v-if="!inputStatusName"
                  ></i>
                  <i
                    class="el-icon-close"
                    @click.stop="handleClose('name')"
                    v-if="inputStatusName"
                  ></i>
                </div>
              </div>
            </template>
            <template slot-scope="scope">
              <span @click.stop="seeMaterial(scope.row)">{{
                scope.row.name
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="型号规格"
            align="center"
            prop="attribute"
            width="150"
          />
          <el-table-column
            label="主计量"
            align="center"
            prop="unitName"
            width="75"
          />
          <el-table-column
            label="供应方式"
            align="center"
            prop="params.inv_supply_type"
            width="100"
          />
          <el-table-column
            label="图纸号"
            align="center"
            prop="drawingNo"
            width="180"
            v-if="isDrawingNo"
          >
          </el-table-column>

          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding"
            width="220"
          >
            <template slot-scope="scope">
              <div class="public-btn">
                <el-button
                  size="mini"
                  type="text"
                  class="basic-see"
                  @click.stop="seeMaterial(scope.row)"
                  v-hasPermi="['inv:items:view']"
                  >查看
                </el-button>
                <el-button
                  size="mini"
                  type="text"
                  @click.stop="updateMaterial(scope.row)"
                  v-hasPermi="['inv:items:edit']"
                  >编辑
                </el-button>
                <el-button
                  size="mini"
                  class="basic-delete"
                  type="text"
                  @click.stop="delMaterial(scope.row)"
                  v-hasPermi="['inv:items:remove']"
                  >删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页信息 -->
        <pagination
          v-show="total >= 19"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getMaterialList"
        />
      </el-col>
    </el-row>

    <!-- 新增/查看/修改物料弹框信息 -->
    <el-dialog
      title="物料信息"
      :visible.sync="open"
      width="600px"
      v-if="open"
      @close="closeDialog"
    >
      <el-form
        ref="materialForm"
        :rules="rules"
        :model="materialForm"
        label-width="80px"
        size="medium"
        :disabled="butChange == '3'"
        :validate-on-rule-change="false"
        :hide-required-asterisk="star"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item
              label="选择分类"
              prop="value"
              v-if="butChange == '2' || butChange == '1'"
            >
              <el-cascader
                v-model="value"
                :options="sortTree"
                ref="classTree"
                :props="classProps"
                @change="handleChange"
                class="cas-input"
                :disabled="butChange == '2'"
              ></el-cascader>
            </el-form-item>
            <el-form-item label="分类信息" prop="value" v-if="butChange == '3'">
              <el-cascader
                v-model="value"
                :options="sortTree"
                ref="classTree"
                :props="classProps"
                @change="handleChange"
                class="cas-input"
                :disabled="butChange == '2'"
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料编码">
              <el-input v-model="materialForm.code" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="butChange == '2' || butChange == '1'">
            <el-form-item label="主计量" prop="unitForm">
              <el-select
                v-model="unitForm"
                placeholder="请选择"
                @change="handleUnit"
              >
                <el-option
                  v-for="(item, index) in unitDate"
                  :key="index"
                  :label="item.name"
                  :value="item.code"
                >
                  <span>{{ item.name }}</span>
                  <span>（{{ item.code }}）</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="butChange == '3'">
            <el-form-item label="更新时间">
              <el-input
                v-model="materialForm.updateTime"
                class="updata-time"
              ></el-input>
            </el-form-item>
          </el-col>
          <!-- 左部开始 -->
          <el-col :span="12">
            <el-col :span="24">
              <el-form-item label="物料名称" prop="name">
                <el-input v-model="materialForm.name"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="butChange == '3'">
              <el-form-item label="主计量" prop="unitForm">
                <el-select
                  v-model="unitForm"
                  placeholder="请选择"
                  @change="handleUnit"
                >
                  <el-option
                    v-for="(item, index) in unitDate"
                    :key="index"
                    :label="item.name"
                    :value="item.code"
                  >
                    <span>{{ item.name }}</span>
                    <span>（{{ item.code }}）</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="型号规格" prop="attribute">
                <el-input v-model="materialForm.attribute"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="规格描述" prop="property">
                <el-input v-model="materialForm.property"></el-input>
              </el-form-item>
            </el-col>
          </el-col>
          <!-- 左部结束 -->
          <!-- 右部开始 -->
          <el-col :span="12">
            <div style="overflow: hidden; margin-right: 10px">
              <div class="ma-right">
                <el-col :span="24">
                  <el-form-item label="供应方式" prop="property">
                    <el-select v-model="materialForm.supplyType" placeholder="">
                      <el-option
                        v-for="item in optionsSupplyType"
                        :key="item.dictValue"
                        :label="item.dictLabel"
                        :value="item.dictValue"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item
                    label="图纸号"
                    prop="drawingNo"
                    v-if="isDrawingNo"
                  >
                    <el-input v-model="materialForm.drawingNo"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item
                    label="允许负库存"
                    prop="enableDebt"
                    style="text-align: right"
                  >
                    <el-switch
                      v-model="materialForm.enableDebt"
                      active-value="1"
                      inactive-value="0"
                    ></el-switch>
                  </el-form-item>
                </el-col>
              </div>
            </div>
          </el-col>
          <!-- 右部结束 -->
        </el-row>
      </el-form>
      <!-- 物料数量表单 -->
      <div class="from-mount" v-if="butChange == 3">
        <el-form
          :model="materialMount"
          label-width="100px"
          size="medium"
          class="mount-form"
          :disabled="butChange == 3"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="当前库存数量" class="txt-right">
                <el-input
                  v-model="materialMount.quantity"
                  class="now-stock"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="实际可用数量" class="txt-right">
                <el-input
                  v-model="materialMount.params.availableQuantity"
                  class="now-actual"
                ></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="锁定库存数量">
                <el-input
                  v-model="materialMount.lockQuantity"
                  class="txt-right"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="在途库存数量">
                <el-input
                  v-model="materialMount.wayQuantity"
                  class="txt-right"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <el-row>
        <el-col :span="12" class="keep-status" v-if="butChange == '1'">
          <el-checkbox v-model="keepName" @change="checkName"
            >保持物料名称</el-checkbox
          >
          <!--  <el-checkbox v-model="keepPeriod" @change="checkPeriod">保持期初</el-checkbox> -->
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer foot-bot" v-if="butChange !== 3">
        <span class="foot-star"
          ><label v-if="butChange == 1"
            ><i class="el-icon-star-on"></i
            >温馨提示：新增成功，可继续添加！</label
          ></span
        >
        <div>
          <el-button
            type="primary"
            v-if="butChange == 1"
            @click="submitForm('materialForm')"
            >确定</el-button
          >
          <el-button
            type="success"
            v-if="butChange == 2"
            @click="submitForm('materialForm')"
            >保存</el-button
          >
          <el-button @click="cancel">取消</el-button>
        </div>
      </span>
    </el-dialog>
    <!-- 物料导入对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="
          upload.url +
          '?updateSupport=' +
          upload.updateSupport +
          '&sortId=' +
          upload.sortId
        "
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox
            v-model="upload.updateSupport"
          />是否更新已经存在的物料数据
          <el-link type="info" style="font-size: 12px" @click="importTemplate"
            >下载模板</el-link
          >
        </div>
        <div class="el-upload__tip" style="color: red" slot="tip">
          提示：仅允许导入“xls”或“xlsx”格式文件！
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { listSort } from "../../api/sort"; //分类接口
import axios from "axios";
import {
  listMaterial,
  addMaterial,
  emptyMaterial,
  deleteMaterial,
  updateMateria,
  listUnit,
  exportMaterial,
  importMateria,
  dictMatching,
} from "../../api/items"; //物料接口
import { getTreeData, getEcho, isAccord } from "../../utils/items"; //js方法
import Tree from "../../components/Sort/tree"; //分类组件
import PrintPage from "../../components/PrintPage"; //打印组件
import print from "print-js"; //打印js
import { supParent } from "../../utils/sort.js"; //打印获取分类名称
export default {
  name: "Items",
  data() {
    // 分类效验规则
    var checkValue = (rule, value, callback) => {
      if (this.value.length == 0) {
        return callback(new Error(""));
      } else {
        callback();
      }
    };
    // 主计量效验规则
    var checkUnit = (rule, value, callback) => {
      if (this.unitForm == "") {
        return callback(new Error(""));
      } else {
        callback();
      }
    };
    return {
      // 遮罩层
      loading: true,
      //物料树遮罩层
      treeLoading: false,
      //分类搜索名称
      searchName: "",
      // 批量删除按钮状态
      multiple: true,
      //是否显示分类操作按钮
      isOperation: true,
      //树形数据
      sortTree: [],
      //树形选中是否高亮
      isHeight: true,
      //物料数据最大高度
      maxHeight: null,
      // 导入/导出/清空按钮状态
      disCuarent: true,
      // 是否保存弹框分类回显数据
      isSava: false,
      //点击分类树中转站
      transferData: {
        sortId: "",
        unitCode: "",
        supplyType: "",
      },
      //搜索参数
      searchForm: {
        searchName: "", //搜索物料名称
        searchCode: "", //搜索物料编码
      },
      // 头部料品搜索
      headerFrom: {
        codeInput: "",
        nameInput: "",
      },
      //头部编码输入框状态
      inputStatusCode: false,
      inputStatusName: false,
      // 料品查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 100,
        type: true,
      },
      // 总条数
      total: 0,
      // 日期范围
      dateRange: [],
      // 料品数据
      basicfileList: [],
      // 新增/修改/编辑对话框状态
      open: false,
      //对话框标题
      dialogTitle: "",
      //必填是否显示*号
      star: false,
      //选择分类回显信息
      value: [],
      //表单禁用状态
      seeStatus: false,
      // 查重地址
      effecUrl: process.env.VUE_APP_BASE_API + "/inv/items/checkDuplicat/",
      //分类选择配置
      classProps: {
        children: "children",
        label: "sortName",
        value: "sortCode",
        checkStrictly: true,
      },
      unitDate: [],
      // 主计量
      unitForm: "",
      // 物料新增/修改信息表单
      materialForm: {
        code: "",
        sortId: "",
        name: "",
        attribute: "",
        property: "",
        enableChip: "0",
        enableDebt: "0",
        supplyType: "",
        drawingNo: "",
      },
      //是否显示图纸号
      isDrawingNo: false,
      //供应方式
      optionsSupplyType: [],
      //验证表单状态
      cationStatus: "blur",
      //保持物料名称/期初状态
      keepName: false,
      keepPeriod: false,
      // 物料导入参数
      upload: {
        // 是否显示弹出层（物料信息导入）
        open: false,
        // 弹出层标题（物料信息导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        //分类id
        sortId: "",
        // 设置上传的请求头部
        headers: {
          Authorization: "Bearer " + getToken(),
        },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/inv/items/import",
      },
      //打印分类名称
      printName: "",
      //打印数据
      printData: [],
      //打印状态
      printShow: false,
      //物料查看数量表单
      materialMount: {},
      //弹框提交按钮状态，1（新增） 2（修改）
      butChange: "",
      // 表单校验
      rules: {
        value: [
          {
            required: true,
            validator: checkValue,
            trigger: "change",
          },
        ],
        name: [
          {
            required: true,
            trigger: "blur",
          },
        ],
        unitForm: [
          {
            required: true,
            validator: checkUnit,
            trigger: "change",
          },
        ],
      },
    };
  },

  created() {
    // 是否显示图纸号
    let path = this.$route.path;
    if (path.indexOf("mach") > -1) {
      this.isDrawingNo = true;
    }
    //初始化分类数据
    this.getTreeList();
    //初始化物料数据
    this.getMaterialList();
    // 初始化主计量
    this.getUnit();
    //供应方式
    this.getSupplyType();
    //隐藏操作按钮
    this.isOperation = false;
  },

  methods: {
    //获取分类数据
    getTreeList() {
      this.treeLoading = true;
      listSort({
        feature: "",
      }).then((res) => {
        this.sortTree = getTreeData(res.data); //当children为0时，赋值undefined
        this.treeLoading = false;
      });
    },

    // 获取物料数据
    getMaterialList() {
      this.loading = true;
      listMaterial(this.queryParams).then((res) => {
        if (res.code == 200) {
          let arrBasic = JSON.parse(JSON.stringify(res.rows));
          this.basicfileList = arrBasic;
          this.total = res.total;
          if (this.basicfileList.length >= 19) {
            //条数总数大于显示出现滚动条
            this.maxHeight = `${document.documentElement.clientHeight}` - 270;
          } else {
            this.maxHeight = "";
          }
          this.loading = false;
        }
      });
    },

    //获取主计量数据
    getUnit() {
      return new Promise((resolve, reject) => {
        this.loading = true;
        listUnit()
          .then((res) => {
            if (res.code == 200) {
              this.unitDate = res.rows;
              this.loading = false;
              resolve();
            }
          })
          .catch((err) => {
            this.msgError("获取主计量失败！");
          });
      });
    },

    //获取供应方式
    getSupplyType() {
      dictMatching("inv_supply_type").then((res) => {
        if (res.code == 200) {
          this.optionsSupplyType = res.data;
        }
      });
    },

    //物料分类点击获取
    nodeClick(node) {
      this.queryParams.name = ""; //避免当搜索物料信息时页面缓存物料名称
      this.queryParams.code = ""; //避免当搜索物料信息时页面缓存物料编码
      this.searchForm.searchName = "";
      this.searchForm.searchCode = "";
      this.queryParams.type = true; //默认模糊查询
      this.queryParams.pageNum = 1; //默认页数
      this.queryParams.pageSize = 100; //默认条数
      this.butChange = "1"; //按钮状态为新增
      this.upload.sortId = node[0].sortId; //导入id
      this.disCuarent = false; //导入/导出/清空按钮状态
      this.transferData.unitCode = node[0].unitCode;
      this.transferData.sortId = node[0].sortId;
      this.transferData.supplyType = node[0].supplyType;
      // 获取上级分类名称
      const name = [];
      const getParentName = supParent(node[1], name).reverse(); //获取上级分类名称
      const parentName = getParentName.join(" / "); //拼接上级分类名称
      if (node[1].data.parentId == 0) {
        this.printName = node[1].data.sortName; //主类上级分类为自身
      } else {
        this.printName = parentName + " / " + node[1].data.sortName; //子类上级分类最终结果
      }
      this.isHeight = true; //打开分类树高亮
      this.queryParams.sortId = node[0].sortId; //赋值sortId用于搜索
      this.getMaterialList(); //重新拉取数据
    },

    //选择主计量
    handleUnit(value) {
      if (this.unitDate.length > 0) {
        let obj = {};
        obj = this.unitDate.find((item) => {
          return item.code === value;
        });
        this.materialForm.unitCode = obj.code; //主计量编码
        this.materialForm.unitName = obj.name; //主计量名称
      }
    },

    // 查询所有
    checkleAll() {
      //清空搜索信息，避免干扰
      this.queryParams.sortId = "";
      this.queryParams.code = "";
      this.queryParams.name = "";
      this.printName = "";
      this.disCuarent = true;
      this.queryParams.type = true;
      this.serchReset(); //重置搜索表单
      this.isHeight = false; //关闭分类树高亮
      this.getMaterialList();
    },

    //搜索物料
    search() {
      if (
        this.searchForm.searchName == "" &&
        this.searchForm.searchCode == ""
      ) {
        this.msgError("物料编码或物料名称不能同时为空！");
      } else {
        this.queryParams.name = this.searchForm.searchName; //赋值物料名称
        this.queryParams.code = this.searchForm.searchCode; //赋值物料编码
        this.queryParams.type = true; //查询类型为模糊查询
        this.queryParams.sortId = ""; //避免当分类树点击时页面缓存的sortId导致搜索失败
        this.getMaterialList();
      }
    },

    // 物料表格头部编码搜索
    handleCodeName(status) {
      this.searchForm.searchName = ""; //清空头部搜索内容
      this.searchForm.searchCode = ""; //清空头部搜索内容
      if (status == "code") {
        //接收参数为code则为编码搜索
        this.inputStatusCode = true; //显示编码搜索框
        this.handleClose("name"); //关闭名称搜索框
      } else if (status == "name") {
        //接收参数为name则为名称搜索
        this.inputStatusName = true; //显示名称搜索框
        this.handleClose("code"); //关闭名称搜索框
      }
    },

    // 物料表格头部编码关闭
    handleClose(status) {
      if (status == "code") {
        this.inputStatusCode = false;
        this.headerFrom.codeInput = "";
      } else if (status == "name") {
        this.inputStatusName = false;
        this.headerFrom.nameInput = "";
      }
    },
    searchCodeName() {
      this.queryParams.name = this.headerFrom.nameInput; //赋值物料名称
      this.queryParams.code = this.headerFrom.codeInput; //赋值物料编码
      this.queryParams.type = false;
      this.inputStatusName = false;
      this.inputStatusCode = false;
      this.queryParams.sortId = ""; //避免当分类树点击时页面缓存的sortId导致搜索失败
      this.getMaterialList();
    },

    // 清空按钮操作
    handlEmpty() {
      this.$confirm(
        "是否清空" + " " + this.printName + " " + "物料信息?",
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          return emptyMaterial(this.upload.sortId);
        })
        .then((res) => {
          this.msgSuccess("清空物料信息成功");
          this.getMaterialList();
          // this.disCuarent = true;
        });
    },

    //点击
    stopReturn() {
      return false;
    },

    // 导入按钮操作
    handleImport() {
      this.upload.title = this.printName + "物料信息导入";
      this.upload.open = true;
    },

    //下载模板操作
    importTemplate() {
      importMateria({
        sortId: this.upload.sortId,
      }).then((response) => {
        this.download(response.msg);
      });
    },

    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },

    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", {
        dangerouslyUseHTMLString: true,
      });
      this.checkleAll();
    },

    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },

    //导出
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所选物料数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportMaterial(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        });
    },

    // 打印
    handlePrint() {
      let number = 1;
      this.printData = this.basicfileList;
      this.printData.forEach((obj) => {
        obj.id = number++;
      });
      setTimeout(() => {
        this.$print(this.$refs.startPrint.$refs.print);
      }, 0);
    },

    // 分类选择回显结果
    handleChange(value) {
      value = value.join(""); //转换成字符串，用于传值后台
      this.materialForm.code = value;
      this.materialForm.sortId =
        this.$refs["classTree"].getCheckedNodes()[0].data.sortId; //赋值sortId
    },

    //新增物料
    addMaterial() {
      this.butChange = "1"; //为1按钮状态为信息
      this.open = true;
      this.star = false;
      this.unitForm = this.transferData.unitCode; //获取默认主计量
      if (this.unitForm !== "") {
        this.handleUnit(this.transferData.unitCode); //得到单位编码与名称字段
      }
      if (this.transferData.sortId !== "") {
        this.undataAddSee(this.transferData.sortId);
      }
      this.resetFrom(); //重置表单，避免修改表单时带来的缓存
      this.isSava = true;
    },

    // 修改物料
    updateMaterial(row) {
      this.star = false;
      this.undataAddSee(row.sortId).then(() => {
        this.butChange = "2"; //为1按钮状态为信息
        this.open = true;
        if (row.sortId !== this.upload.sortId) {
          this.isSava = false; //不保存弹框回显数据
        }
        this.unitForm = row.unitCode;
        this.handleUnit(row.unitCode); //得到主计量与计量编码

        this.materialForm = Object.assign({}, row); //拷贝物料信息
      });
    },

    //查看物料
    seeMaterial(row) {
      this.butChange = "3"; //为1按钮状态为信息
      this.star = true;
      if (row.sortId !== this.upload.sortId) {
        this.isSava = false; //不保存弹框回显数据
      }
      this.materialForm = Object.assign({}, row); //拷贝物料信息
      this.undataAddSee(row.sortId).then(() => {
        // 格式化4位小数
        let basicMount = JSON.parse(JSON.stringify(row));
        basicMount.mp = this.Decimal(basicMount.mp);
        basicMount.lockQuantity = this.Decimal(basicMount.lockQuantity);
        basicMount.wayQuantity = this.Decimal(basicMount.wayQuantity);
        basicMount.quantity = this.Decimal(basicMount.quantity);
        basicMount.params.availableQuantity = this.Decimal(
          basicMount.params.availableQuantity
        );
        this.materialMount = basicMount;
        this.open = true;
        this.unitForm = row.unitCode;
        this.butChange = 3; //改变表单状态
      });
    },

    // 新增/修改/查看公共获取分类回显
    undataAddSee(id) {
      return new Promise((resolve, reject) => {
        let parentArr = [], //用于储存父类分类信息
          childrenArr = []; ////用于储存子类分类信息
        getEcho(id, this.sortTree, parentArr, childrenArr).then((res) => {
          setTimeout(() => {
            let success = [];
            for (let i = 0; i < res.length; i++) {
              if (success.indexOf(res[i]) === -1) {
                success.push(res[i]);
              }
            }
            let getNode = JSON.parse(JSON.stringify(success)); //拷贝vuex信息，避免影响源数据
            getNode.forEach((v) => {
              if (v.ancestors.indexOf(",") > -1) {
                //是否是子分类
                v.ancestors = v.ancestors.split(",").length; //拼接数组长度，用于排序
              } else {
                v.ancestors = 1;
              }
            });
            getNode.sort((a, b) => {
              //排序得到正常的分类顺序，用于得到sortCode
              return a.ancestors - b.ancestors;
            });
            let getCode = [];
            getNode.forEach((code) => {
              getCode.push(code.sortCode);
              this.materialForm.sortId = code.sortId;
            });
            this.value = getCode; //对话框分类回显
            if (this.butChange == "1") {
              //状态为新增物料
              getCode = getCode.join(""); //转换成字符串，用于传值后台
              this.materialForm.code = getCode;
            }
          }, 0);
        });
        resolve();
      });
    },

    //删除物料
    delMaterial(row) {
      this.$confirm("确认删除", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return deleteMaterial(row.code);
        })
        .then((res) => {
          if (res.code == 200) {
            this.msgSuccess("删除成功");
            this.getMaterialList();
            this.resetDilog(); //重置表单
          }
        });
    },

    //提交新增修改物料表单
    submitForm(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          if (this.butChange == "1") {
            let subForm = {
              //重新赋值表单，避免修改时弹框的属性干扰
              code: this.materialForm.code,
              sortId: this.materialForm.sortId,
              name: this.materialForm.name,
              attribute: this.materialForm.attribute,
              unitCode: this.materialForm.unitCode,
              unitName: this.materialForm.unitName,
              property: this.materialForm.property,
              enableBatch: this.materialForm.enableBatch,
              enableChip: this.materialForm.enableChip,
              enableDebt: this.materialForm.enableDebt,
              supplyType: this.materialForm.supplyType,
              drawingNo: this.materialForm.drawingNo,
            };
            addMaterial(subForm)
              .then((res) => {
                if (res.code == 200) {
                  this.msgSuccess("新增成功");
                  if (this.keepName == true) {
                    //保持物料名称不保持期初
                    this.$refs.materialForm.clearValidate(); //第一次改变不立即触发验证
                    this.isKeepName();
                  } else {
                    this.resetFrom();
                    this.$refs.materialForm.resetFields(); //清除表单验证
                  }
                  this.getMaterialList();
                }
              })
              .catch((err) => {
                this.msgError("新增失败");
              });
          } else {
            updateMateria(this.materialForm)
              .then((res) => {
                //触发保存提交
                if (res.code == 200) {
                  this.msgSuccess("修改成功");
                  this.getMaterialList();
                  this.open = false;
                }
              })
              .catch((err) => {
                this.msgError("修改失败");
              });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    //查重
    btnDuplicat() {
      axios({
        methods: "get",
        url: this.effecUrl,
        params: {
          sortId: this.upload.sortId,
        },
        headers: {
          Authorization: "Bearer " + getToken(),
        },
      }).then((res) => {
        this.$alert(res.data.msg, "查重结果", {
          dangerouslyUseHTMLString: true,
        });
      });
    },

    // 关闭弹框
    closeDialog() {
      this.resetDilog();
      this.resetSelector();
    },

    //解决级联选择器回显高亮异常问题
    resetSelector() {
      if (this.$refs.classTree) {
        this.$refs.classTree.$refs.panel.activePath = [];
        this.$refs.classTree.$refs.panel.calculateCheckedNodePaths();
      }
    },

    //搜索表单重置
    serchReset() {
      for (let key in this.searchForm) {
        this.searchForm[key] = "";
      }
    },

    // 弹框新增清空表单
    resetFrom() {
      this.materialForm.name = ""; //物料名称清空
      this.materialForm.attribute = ""; //型号规格清空
      this.materialForm.property = ""; //货位清空
      this.materialForm.drawingNo = "";
      this.materialMount = {};
      if (this.transferData.supplyType !== "") {
        this.materialForm.supplyType = this.transferData.supplyType;
      } else {
        this.materialForm.supplyType = "0";
      }

      this.materialForm.enableBatch = "0";
      this.materialForm.enableChip = "0";
      this.materialForm.enableDebt = "0";
    },

    //保持物料按钮
    checkName(value) {
      this.keepName = value;
    },

    //保持物料名称
    isKeepName() {
      this.materialForm.attribute = ""; //型号规格清空
      this.materialForm.property = ""; //货位清空
      setTimeout(() => {
        this.$refs.materialForm.clearValidate(); //清除表单验证
      }, 30);
    },

    // 弹框叉号关闭
    resetDilog() {
      if (this.isSava == false) {
        this.value = []; //重置分类
        this.materialForm.code = "";
      }

      this.keepName = false;
      this.keepPeriod = false;
      this.resetFrom();
    },

    //弹框取消
    cancel() {
      this.open = false;
      this.resetDilog();
    },
  },

  components: {
    Tree,
    PrintPage,
  },
};
</script>
<style lang="scss">
.el-table {
  overflow: inherit;
}

.basicfile-box {
  .el-tree--highlight-current
    .el-tree-node.is-current
    > .el-tree-node__content {
    color: #1890ff;
  }

  .ma-right {
    .el-form-item {
      display: flex;
      align-items: center;
      justify-content: flex-end;
    }
    label {
      width: auto;
      flex-grow: 1;
      flex-shrink: 0;
    }

    .el-form-item__content {
      margin-left: 0px !important;
      margin-right: 0 !important;
    }
  }

  .height-tree2 {
    height: calc(100vh - 165px);
  }

  .el-table .el-table__header-wrapper th,
  .el-table .el-table__fixed-header-wrapper th {
    height: 35px;
  }

  .el-table__header,
  .el-table .cell,
  .basicfile-box .has-gutter th,
  .el-table thead {
    overflow: inherit !important;
  }

  // 下拉收起动画
  .toggle-fade {
    transition: all 0.1s linear;
    overflow: hidden;
  }

  .toggle-fade-enter-active {
    animation: downOpen 0.2s linear;
    overflow: hidden;
  }

  .toggle-fade-leave-active {
    animation: downOpen 0.2s reverse linear;
    overflow: hidden;
  }

  @keyframes downOpen {
    from {
      height: 0px;
    }

    to {
      height: 60px;
    }
  }

  .el-table tr td {
    cursor: pointer;
  }

  // .has-gutter th:nth-of-type(8) {
  //   border-right: none;
  // }

  // .el-table__body-wrapper tr td:nth-of-type(8) {
  //   border-right: none;
  // }

  .txt-right {
    input {
      text-align: right;
    }
  }

  .el-table__header-wrapper,
  .el-table__footer-wrapper {
    overflow: inherit;
  }

  .operation-btn {
    .is-disabled {
      span {
        font-weight: 700;
      }
    }
  }

  .el-table--medium th,
  .el-table--medium td {
    overflow: inherit;
  }

  .el-table th > .cell {
    overflow: inherit;
    position: relative;
  }

  .caret-wrapper {
    position: absolute;
    right: 64px;
    top: -5px;
    display: none;
  }

  .el-button--info.is-plain.is-disabled {
    color: #adaeaf;
  }

  .search-box {
    .search-header {
      display: flex;
      align-items: center;
      justify-content: center;

      span {
        width: 65px;
        display: inline-block;
        flex-shrink: 0;
      }

      .el-input--mini .el-input__inner {
        padding-right: 10px;
        padding-left: 10px;
      }

      i {
        font-size: 14px;
        cursor: pointer;
      }

      .el-icon-close {
        font-size: 15px;
        color: #999;
      }
    }

    .box-input {
      position: absolute;
      top: 30px;
      z-index: 999;
      left: 0px;
      right: 0px;
      background: #fff;
      height: 60px;
      box-shadow: 1px 1px 5px #eee;

      .input-t {
        padding: 15px;
      }
    }
  }

  .cas-input input {
    color: #1890ff !important;
  }

  .keep-status {
    margin-top: 15px;
  }

  .updata-time {
    input {
      border: none;
    }
  }

  .el-cascader .el-input .el-input__inner {
    color: #1890ff;
  }

  .el-input--suffix input {
    color: #606266;
  }

  .el-cascader--medium {
    width: 100%;
  }

  .has-gutter th {
    text-align: center;
    overflow: inherit;
  }

  .el-dialog__body {
    padding-right: 20px;
    padding-bottom: 20px;
  }

  .now-stock {
    input {
      color: #1890ff !important;
    }
  }

  .now-actual input {
    color: #13ce66 !important;
  }

  .el-input.is-disabled .el-input__inner {
    color: #333;
  }

  .el-form-item--medium .el-form-item__content {
    margin-right: 10px;
  }

  .cell {
    padding-right: 14px !important;
    padding-left: 14px !important;

    .basic-delete {
      color: #f56c6c;
    }

    .basic-see {
      color: #67c23a;
    }

    button:hover i {
      font-weight: 700;
    }

    button:hover span {
      font-weight: 700;
    }
  }

  .from-mount {
    padding: 15px;
    box-shadow: 1px 1px 10px 1px #eee;
    border-radius: 5px;
    padding-bottom: 10px;
    margin: 10px 10px 0px 10px;

    h3 {
      font-weight: normal;
      font-size: 15px;
      margin-top: 0;
      text-align: center;
      color: #1890ff;
    }
  }

  .foot-bot {
    text-align: inherit !important;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .foot-star {
      color: #1682e6;

      label {
        font-weight: normal;
        font-size: 12px;
      }
    }
  }
}
</style>
